import koa from 'koa';
// import path from 'path';
import JWT from 'koa-jwt';
import bodyParser from 'koa-bodyparser';
import json from 'koa-json';
import cors from '@koa/cors'
import compose from 'koa-compose';
import errorHandler from './common/errorHandler';
import router from './routes/router';
import { dictionaries } from '@/utils/dictionaries';
import { logger, accessLogger } from '@/utils/logger';

(async () => {
    const JWT_SECRET = await dictionaries('get', 'JWT_SECRET');
    const jwt = JWT({ secret: JWT_SECRET[0].value }).unless({
        path: [
            /\/user/,
            /\/admin/
        ]
    });
    const bodyparser = bodyParser({
        enableTypes: ['json', 'form', 'text']
    });
    const middleware = compose([
        accessLogger(),
        errorHandler,
        bodyparser,
        cors(),
        json(),
        router(),
        jwt
    ]);
    const port = 3000;
    const app = new koa();
    app.use(middleware);
    app.listen(port, () => {
        console.log('This server is running at http://localhost:' + port);
    });

    app.on('error', err => {
        logger.error(err);
    });
})();